#include "qshake.h"
#include <math.h>

QShake::QShake(QObject * parent) :
    QObject(parent)
  , module(0)
  , m_sensitivity(QShake::Medium)
  , m_direction(QShake::All)
{
    sensor.addFilter(this);
}

void QShake::start() {
    sensor.start();
}


void QShake::stop() {
    sensor.stop();
}

float QShake::sensitivity() const{
    return this->m_sensitivity;
}

void QShake::setSensitivity(float value){
    this->m_sensitivity = value;
}

QShake::Direction QShake::direction() const{
    return this->m_direction;
}

void QShake::setDirection(QShake::Direction value){
    this->m_direction = value;
}

bool QShake::filter(QAccelerometerReading *reading)
{
    qreal rx = reading->x();
    qreal ry = reading->y();
    qreal rz = reading->z();
    qreal c_sensitivity = ( m_direction == QShake::All ) ? m_sensitivity : m_sensitivity*1.5;

    qreal cmodule = 0;
    switch(m_direction) {
    case QShake::UpDown    : cmodule = sqrt(ry * ry * 3); break;
    case QShake::LeftRight : cmodule = sqrt(rx * rx * 3); break;
    case QShake::PushPull  : cmodule = sqrt(rz * rz * 3); break;
    default: cmodule = sqrt(rx * rx + ry * ry + rz * rz); break;
    }

    float cshake = sqrt(pow(module,2)+pow(cmodule,2));

    if( cshake > c_sensitivity ) {
        emit shake(true);
    } else {
        emit shake(false);
    }

    module = cmodule;

    return false;
}
